using System.Text;
using imitateMacQQ.WebApi.Repository.Redis;
using Microsoft.AspNetCore.Mvc;

namespace imitateMacQQ.WebApi.Api.WebSocket;

[ApiController]
[Route("api/[controller]/[action]")]
public class WebSocketController : ControllerBase
{
    private readonly Utils _utils;

    public WebSocketController(Utils utils)
    {
        _utils = utils;
    }

    [HttpGet]
    public async Task GetNotReadCount(string token)
    {
        if (await _utils.GetAuth(token))
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                await Echo(webSocket);
            }
            else
            {
                HttpContext.Response.StatusCode = 400;
            }
        }
    }

    private async Task Echo(System.Net.WebSockets.WebSocket webSocket)
    {
        var buffer = new byte[1024 * 4];
        var result = await webSocket.ReceiveAsync(
            new ArraySegment<byte>(buffer),
            CancellationToken.None);
        while (!result.CloseStatus.HasValue)
        {
            //var serverMsg = Encoding.UTF8.GetBytes($"{Encoding.UTF8.GetString(buffer)}");
            var account = Encoding.UTF8.GetString(buffer)
                .Trim('\r').Trim('\n').Trim().Replace("NUL", "");
            account = account.Remove(13);
            var data = RedisProtect.Get(account);
            if (string.IsNullOrEmpty(data))
                data = "NUll_Data";
            var serverMsg = Encoding.UTF8.GetBytes(data);
            await webSocket.SendAsync(
                new ArraySegment<byte>(
                    serverMsg, 0, serverMsg.Length),
                result.MessageType,
                result.EndOfMessage,
                CancellationToken.None);
            buffer = new byte[1024 * 4];
            result = await webSocket.ReceiveAsync(
                new ArraySegment<byte>(buffer),
                CancellationToken.None);
        }

        await webSocket.CloseAsync(result.CloseStatus.Value,
            result.CloseStatusDescription,
            CancellationToken.None);
    }
}